﻿using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;

namespace System
{
    public static class JsonExtension
    {
        /// <summary>
        /// JSON字符串转对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns>返回转换成功后的指定类型对象</returns>
        public static T JsonToObj<T>(this string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }

        /// <summary>
        /// 对象转JSON字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns>返回转换后的JSON字符串</returns>
        public static string ToJson<T>(this T obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// 对象转JSON字符串然后格式化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns>返回转换格式化后的JSON字符串</returns>
        public static string ToFormatJson<T>(this T obj)
        {
            return JsonConvert.SerializeObject(obj, Formatting.Indented);
        }

        /// <summary>
        /// 深拷贝对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T DeepClone<T>(this T obj)
        {
            return obj.ToJson().JsonToObj<T>();
        }

        /// <summary>
        /// JSON 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="_JSONString"></param>
        /// <returns></returns>
        public static T JSONStringToObject<T>(this String _JSONString) where T : class
        {
            if (string.IsNullOrEmpty(_JSONString))
            {
                return default(T);
            }
            return JsonConvert.DeserializeObject<T>(_JSONString);
        }

        /// <summary>
        /// JSON 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T ToObject<T>(this string json)
        {
            if (string.IsNullOrEmpty(json))
            {
                return default(T);
            }
            return JsonConvert.DeserializeObject<T>(json);
        }
    }
}